package database;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.Transaction;

import database.model.Article;
import database.model.Section;

public class DataBaseStore {
	private static DataBaseStore sDefaultStore;
	//-----------------------------------------------------------------------------------------------------------------------------
	public static DataBaseStore defaultStore()
	{
		if(sDefaultStore == null)
		{
			sDefaultStore = new DataBaseStore();
		}
		return sDefaultStore;
	}
	//-----------------------------------------------------------------------------------------------------------------------------
	public List<Article> getArticlesForSection(Section section)
	{
		Session session = HibernateUtil.currentSession();
		Transaction trans = session.beginTransaction();
		@SuppressWarnings("unchecked")
		List<Article> res = session.createSQLQuery("select * from PERSON WHERE name = '"+section.getTitle()+"'").addEntity(Section.class).list();
		trans.commit();
		HibernateUtil.closeSession();
		return  res;
	}
	//-----------------------------------------------------------------------------------------------------------------------------
	public void clean()
	{
		Session session = HibernateUtil.currentSession();
		Transaction trans = session.beginTransaction();
		@SuppressWarnings("unchecked")
		List<Section> sections = session.createCriteria(Section.class).list();
		for(Section s:sections)
		{
			s.setArticles(null);
			session.delete(s);
		}
		
		List<Article> articles = session.createCriteria(Article.class).list();
		
		for(Article a: articles)
		{
			session.delete(a);
		}
		
		trans.commit();
		HibernateUtil.closeSession();
	}
}